<template>
  <div>
    <div class="dis-flex flex-lm">
      <span>添加工作台/应用</span>
      <el-button type="text" style="margin-left:2em;" @click="open()">添加</el-button>
      <!-- <template v-if="isDev">{{ JSON.stringify(current) }}</template> -->
    </div>
    
    <ul class="tarList" v-if="targatList.length > 0">
      <li class="tarItem" v-for="(item,k) in targatList" :key="k">
        <span :class=" isDev?item[0].type:'' ">
          <template v-if="Boolean(item[0])">{{ isDev?item[0].id:item[0].name}}</template>
          <template v-if="Boolean(item[1])">- {{ isDev?item[1].id:item[1].name}}</template>
          <template v-if="Boolean(item[2])">- {{ item[2] | getLv3Targer }}</template>
        </span>
        <el-button type="text" @click="removeTargert(k)">删除</el-button>
      </li>
    </ul>
    
    <el-dialog title="添加工作台/应用" :visible.sync="dialogVisible" append-to-body width="984px">
      <el-row :gutter="24">
        <el-col :span="6">
          <div class="title">工作台</div>
          <div class="dataList">
            <ul class="list">
              <template v-for="item in comPlatformList">
                <li :class="{item:true,active:item.id == current[0].id,disabled:item.disabled}"
                  :key="item.id" @click="selectItem(0,item)">
                  {{ isDev?item.id:item.name }}
                </li>
              </template>
            </ul>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="title">应用选择</div>
          <div class="dataList">
            <ul class="list" v-if="comAppList.length > 0">
              <template v-for="item in comAppList">
                <li :class="{item:true,active:item.id == current[1].id}"
                  :key="item.id" @click="selectItem(1,item)">
                  {{ isDev?item.id:item.name }}
                </li>
              </template>
            </ul>
            <el-empty v-else description="该平台下无相关应用"></el-empty>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="title">
            <el-dropdown :hide-on-click="true"
              placement="bottom-start" :trigger="'click'" @command="handleCommand">
              <span class="el-dropdown-link text-blue btn">
                组织架构<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="tree">组织架构</el-dropdown-item>
                <el-dropdown-item command="label">客户标签</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-checkbox v-if="current[1].id" v-model="isAtAll">全选</el-checkbox>
          </div>
          <div class="dataList">
            
            <template v-if="(orgType == 'tree')">
              <el-tree ref="tree" :indent="4" :data="orgTree" :props="treeProps" v-loading="treeLoading"
                node-key="id" :show-checkbox="true" :check-strictly="false"
                :expand-on-click-node="false"
                :highlight-current="true">
                <div class="custom-tree-node dis-flex flex-sbc" style="width:100%;" slot-scope="{ node,data }">
                  <span>
                    <i class="fa fa-fw fa-folder-open" v-if="data.isParty"></i>
                    <i class="fa fa-fw fa-user" v-if="!data.isParty"></i>
                    {{ node.label }}
                    <template v-if="isDev">{{data.id}}</template>
                  </span>
                  <span v-if="isDev">{{ data.userId }}</span>
                </div>
              </el-tree>
            </template>
            <template v-if="(orgType == 'label')">
              <ul class="list">
                <template v-for="item in orgLabel">
                  <li class="item" :key="item.id">
                    <el-checkbox v-model="item.checked">{{ item.name}}</el-checkbox>
                  </li>
                </template>
              </ul>
            </template>
            <div v-if="isAtAll" class="cover"></div>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="confirm()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';

export default {
  computed:{
    ...mapState(['conditional',]),//只需要companyEmployeeId就够了
    comPlatformList:function(){
      let isAll = this.authorityLimited.isAll;
      let list = this.authorityLimited.list.map((v)=>{
        return v.esCompanyId
      });
      return this.workBenchList.map((v,i,a)=>{
        v.disabled = !(isAll || list.includes(v.id))
        return v;
      })//这里获取二段过滤
    },
    comAppList:function(){
      if(!this.current[0]){return [];}
      let platform = this.comPlatformList.filter((v)=>{
        return (v.id == this.current[0].id)
      })[0];
      let appList = platform.list.map((v)=>{
        return {id:v.agentid,name:v.name,}
      });//这里获取二段过滤
      return appList;
    }
  },
  props:{
    workBenchList:Array,//工作台,请求后的缓存,
    authorityLimited:{
      isAll:Boolean,
      list:Array,
    },
    targetArr:{
      type:Array,
      default:function(){
        return new Array();
      }
    }
  },
  data(){
    return{
      isDev:process.env.NODE_ENV== 'development',
      isAtAll:false,
      platformID:{id:'',name:''},
      // workBenchList:[],
      treeLoading:false,
      current:[false,false],//缓存当前选择
      orgType:['tree','label'][0],
      orgTree:[],
      treeProps: {
        children: 'children',
        label: 'label'
      },
      orgLabel:[],
      targatList:[],
      dialogVisible:false,
    }
  },
  filters:{
    getLv3Targer:function(node){
      let t = process.env.NODE_ENV== 'development';
      if(node.type === '@all'){
        return node.name
      }
      if(['tree','leaf'].includes(node.type)){
        let a = node.path.map((v)=>{return t?v.id:v.name})
        return a.join(' - ')
      }else{
        let a = node.group.map((v)=>{return t?v.id:v.name})
        return a.join(' / ')
      }
    },
  },
  methods:{
    handleCommand(command) {
      this.orgType = command;
    },//切换组织tree和标签label,用$store管理
    test:function(){
      let w = this.$refs.tree.getCheckedNodes(true,false)
      console.log(q)
      console.log(w)
    },
    open:function(){
      this.dialogVisible = true;
    },
    close:function(){
      this.isAtAll = false
      this.orgTree.splice(0, this.orgTree.length);
      this.orgLabel.splice(0, this.orgLabel.length);
      this.current.splice(0,3,false,false);//清空三个指针并填充三个 false 便于处理
      this.dialogVisible = false;
      if(this.targatList.length>0){
        this.$emit('stepChange',1);
      }else{
        this.$emit('stepChange',0);
      }
    },
    confirm:function(){
      let tVue = this
      if( this.isAtAll ){
        let α = {type:'@all',id:tVue.current[0].id, name:tVue.current[0].name,}; //platform
        let β = {type:'@all',id:tVue.current[1].id, name:tVue.current[1].name,}
        let γ = {type:'@all',path:'@all',id:'@all',name:'@all',}
        tVue.targatList.push( [ α,β,γ ] )
      }else{
        if(this.orgType == 'tree'){
          // let w = this.$refs.tree.getCheckedNodes(true,false)
          let q = this.getTreeMin()
          q.forEach((v)=>{
            console.log(v)
            let α = {type:v.isParty?'tree':'leaf',id:tVue.current[0].id, name:tVue.current[0].name,}; //platform
            let β = {type:v.isParty?'tree':'leaf',id:tVue.current[1].id, name:tVue.current[1].name,}
            let γ = {type:v.isParty?'tree':'leaf',path:v.path,id:v.id,name:v.label,}
            tVue.targatList.push( [ α,β,γ ] )
          })
        }
        if(this.orgType == 'label'){
          let q = this.orgLabel.filter((v)=>{
            return v.checked
          })
          let α = {type:'label',id:tVue.current[0].id, name:tVue.current[0].name,}; //platform
          let β = {type:'label',id:tVue.current[1].id, name:tVue.current[1].name,}
          let γ = {type:'label',group:q.map((v)=>{
            return {id:v.id,name:v.name}
          }), }
          tVue.targatList.push( [ α,β,γ ] )
        }
      }
      this.close();
    },
    cancel:function(){
      this.close();
    },
    removeTargert(idx){
      this.targatList.splice(idx,1)
      if(this.targatList.length>0){
        this.$emit('stepChange',1);
      }else{
        this.$emit('stepChange',0);
      }
    },
    clearTargets(){
      this.targatList.splice(0,this.targatList.length)
      if(this.targatList.length>0){
        this.$emit('stepChange',1);
      }else{
        this.$emit('stepChange',0);
      }
    },
    selectItem:function(idx,item){
      if(item.disabled){return}
      this.current.splice(idx,1,JSON.parse(JSON.stringify({
        id:   item.id,
        name: item.name
      })))
      if( idx == 0 ){this.current.splice(1,1,false)};//清空二级指针
      if( idx == 1 ){
        this.getOrgTree();
        this.getOrgLabel();
      };//获取部门结构
    },
    getOrgTree:function(){
      let self = this;
      let opt = {
        eSCompanyId:  self.current[0].id,
        agentid:      self.current[1].id,
        employeeId:   self.conditional.companyEmployeeId,
        state:0,partyId:0,
      }
      console.log('请求tree',opt)
      self.treeLoading = true;
      this.$api.getOrgTree(opt).then((res)=>{
        if(res.data.code !== 200){throw 'error'}
        let resdata = res.data.data.agentAllowPartyList;
        function setChild(tree, json, arrParentPathName) {
          let pNode = json.agentAllowUserList;
          let pLen = Array.isArray(pNode) ? pNode.length : 0;
          let uNode = json.agentAllowPartyList;
          let uLen = Array.isArray(uNode) ? uNode.length : 0;
          let obj = {
            id: json.partyid || json.usersId,
            isParty:Boolean(json.partyid),
            label : json.partyName || json.name,
            disabled: (("isAllow" in json) ? !json.isAllow : false),
          }
          obj.path = arrParentPathName.concat([{
            id:obj.id,
            name:obj.label,
          }]);
          if ((pLen + uLen) > 0) {
            obj.children = new Array();
          }
          if (pLen > 0) {
            for (let i in pNode) {
              setChild(obj.children, pNode[i], obj.path)
            }
          }
          if (uLen > 0) {
            for (let i in uNode) {
              setChild(obj.children, uNode[i], obj.path)
            }
          }
          tree.push(obj)
          return tree;
        }
        let tree = resdata.map((v) => { return setChild([], v, [])[0] });
        self.orgTree.splice(0, self.orgTree.length);
        self.orgTree.push( tree[0] )
        self.treeLoading = false;
      }).catch((err)=>{
        console.error(err)
      })
    },
    getOrgLabel:function(){
      let self = this;
      let opt = {
        eSCompanyId:  self.current[0].id,
        agentid:      self.current[1].id,
      }
      // console.log('请求label',opt)
      this.$api.getLabelList(opt).then((res)=>{
        let list = res.data.data.map((v) => {
          return {
            id: v.tags_Id,
            name:v.tags_Name,
            checked:false,
          }
        })
        self.orgLabel.splice(0,self.orgLabel.length);
        list.forEach((v)=>{
          self.orgLabel.push(v)
        })
      })
    },
    getTreeMin:function(){
      let q = this.$refs.tree.getCheckedNodes(false,false).filter((v)=>{
        return !v.disabled;
      });
      let nArr = q.reduce((t,v,i,a)=>{
        if(i == 0){
          return t.concat(v)
        }else{
          let arrPid = v.path.map((sv)=>{return sv.id})
          if( !( arrPid.includes( t[t.length - 1].id ) ) ){
            return t.concat(v)
          }else{
            return t
          }
        }
        
      },[])
      console.log('%c [ nArr ]-352', 'font-size:13px; background:pink; color:#bf2c9f;', nArr)
      return nArr
    },
    batchGetMediaId:function(){
      // this.$api.getGetMediaId({
      //   esCompanyId:'',
      //   qiniuUrl :'',
      //   mediaType :'',
      //   mediaName:'',
      // })
    },
    
  },
  mounted(){
  }
}
</script>

<style lang="less" scoped>
@import url('../../assets/config.less');
@import url('../../assets/style.less');
.title{
  font-weight: bold;
  font-size:16px;
  line-height: 46px;
  text-align: center;
  color:#111;
}
.dataList{
  width:100%;
  height:400px;
  background:#fafafa;
  overflow: auto;
  .list{
    .item{
      font-size:14px;
      line-height:30px;
      padding:0 unit((@defPadding / 2),px);
      color:#333;
      cursor: pointer;
      &.disabled{color:#999;cursor:not-allowed;}
      &.active{background-color:@blue;color:#fff;}
    }
  }
  .cover{
    position: absolute;
    top:0;bottom:0;left:0;right:0;
    background-color:rgba(255,255,255,0.3);
    cursor: not-allowed;
  }
}

.tree{
  color:green;
}
.leaf{
  color:blue;
}
.label{
  color:red;
}
</style>